package com.xinhe.web.service;

import com.alibaba.fastjson.JSONObject;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.reposity.*;
import com.xinhe.web.request.*;
import com.xinhe.web.response.OrderBuyerView;
import com.xinhe.web.response.OrderBuyerViewSon;
import com.xinhe.web.response.OrderDetailView;
import com.xinhe.web.response.OrderView;
import com.xinhe.web.session.UserSessionManager;
import com.xinhe.web.util.DateUtil;
import com.xinhe.web.util.Express100Util;
import com.xinhe.web.util.Snowflake;
import com.xinhe.web.weixin.WeixinRefundModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private OrderAddressRepository orderAddressRepository;
    @Autowired
    private OrderAddressService orderAddressService;
    @Autowired
    private OrderItemRepository orderItemRepository;
    @Autowired
    private OrderLogisticsRepository orderLogisticsRepository;
    /*@Autowired
    private IValueConfigCache valueConfigCache;*/
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderPayRepository orderPayRepository;
    /*@Autowired
    private WeixinJsapiTradeService weixinJsapiTradeService;*/
    @Autowired
    private SellerShopRepository sellerShopRepository;
    /*@Autowired
    private IUserSessionManager userSessionManager;*/
    @Autowired
    private MemberCouponRepository memberCouponRepository;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private SeckillGoodsRepository seckillGoodsRepository;
    @Autowired
    private SeckillTimeRepository seckillTimeRepository;
    @Autowired
    private TeamGoodsRepository teamGoodsRepository;
    @Autowired
    private AddressRepository addressRepository;
    @Autowired
    private GoodsPriceRepository goodsPriceRepository;
    /*@Autowired
    private AssetCountService assetCountService;*/
    @Autowired
    private ShopRepository shopRepository;
    @Autowired
    private OrderItemService orderItemService;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    @Autowired
    WeixinTradeService weixinTradeService;
    @Autowired
    UserSessionManager userSessionManager;

    public QueryResults<OrderView> pageOrder(Long userId, String orderType, String orderStatus,
                                             String code, int pageNum, int pageSize) {
        QOrder qOrder = QOrder.order;
        QSellerShop qSellerShop = QSellerShop.sellerShop;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(userId)){
            builder.and(qOrder.userId.eq(userId));
        }
        if (StringUtils.isNotBlank(orderStatus)){
            builder.and(qOrder.status.eq(orderStatus));
        }
        if (StringUtils.isNotBlank(orderType)){
            builder.and(qOrder.type.eq(orderType));
        }
        return queryFactory.select(
                        Projections.bean(
                                OrderView.class,
                                qOrder.shopId,
                                qOrder.status,
                                qOrder.userId,
                                qOrder.sellerUserId,
                                qOrder.code,
                                qOrder.payTime,
                                qOrder.payChannel,
                                qOrder.orderAmount,
                                qOrder.orderFee,
                                qOrder.orderPayFee,
                                qOrder.opexManagerFee,
                                qOrder.goodsFee,
                                qOrder.freightFee,
                                qOrder.preferentialFee,
                                qOrder.type,
                                qOrder.distributionType,
                                qOrder.buyerRemark,
                                qOrder.remindSendTime,
                                qOrder.sendTime,
                                qOrder.remindSendTime,
                                qSellerShop.mobile,
                                qSellerShop.name.as("userName")
                        )
                ).from(qOrder)
                .leftJoin(qSellerShop).on(qOrder.sellerUserId.eq(qSellerShop.fUserId))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }
    public Result<OrderDetailView> detailOrder(Long orderId) {
        Order order = this.orderRepository.findById(orderId).get();
        if (order == null) {
            return Result.failed(8001,"订单信息不存在");
        }
        OrderDetailView view = new OrderDetailView();
        BeanUtils.copyProperties(order, view);
        view.setType(order.getType());
        view.setDistributionType(order.getDistributionType());
        view.setStatus(order.getStatus());

        SellerShop sellerShop = this.sellerShopRepository.findByUserId(view.getSellerUserId());
        if (sellerShop != null) {
            view.setSellerShopName(sellerShop.getName());
            view.setSellerIconPath(sellerShop.getIconPath());
        }
        List<OrderItem> orderItems = this.orderItemRepository.findByOrderId(view.getId());
        view.setOrderItems(orderItems);

        if (order.getDistributionType().equals("MAIL")) {
            OrderAddress orderAddress = this.orderAddressService.findByOrderIdAndType(view.getId(),"COMMON");
            view.setOrderAddress(orderAddress);
        } else if (order.getDistributionType().equals("ONESELF_TAKE")) {
            Shop shop =this.shopRepository.findById(view.getShopId()).get();
            view.setShop(shop);
        }
        return Result.ok(view);
    }

    @Transactional
    public Result cancelOrder(Long orderId) {
        Optional<Order> optionalOrder = this.orderRepository.findById(orderId);
        if (!optionalOrder.isPresent()) {
            return Result.failed(2001,"订单不存在");
        }
        Order order = optionalOrder.get();
        if ("UN_PAY".equals(order.getStatus())) {
            order.setStatus("CANCEL");
            this.orderRepository.saveAndFlush(order);
            return Result.ok();
        } else if ("PAYED".equals(order.getStatus())) {
            OrderPay orderPay = this.orderPayRepository.findOneByOrderId(order.getId());
            if (orderPay != null) {
                log.info("进来退款了");
                WeixinRefundModel weixinRefundModel = new WeixinRefundModel();
                weixinRefundModel.setFee(orderPay.getPayMoney());
                weixinRefundModel.setDataId(orderPay.getOrderId());
                weixinRefundModel.setParams(new HashMap<>());
                weixinRefundModel.setBody("订单退款");
                weixinRefundModel.setTradeId(orderPay.getTradeId());
                weixinRefundModel.setDataType("订单退款");
                weixinRefundModel.setNotifyUrl("/orderPay/responseWeixinRefundOrderNotify");
                Result result = this.weixinTradeService.requestWeixinRefund(weixinRefundModel);
                //退款成功
                if (0 == result.getCode()){
                    order.setStatus("CANCEL");
                    this.orderRepository.saveAndFlush(order);
                    return Result.ok();
                }else {
                    return result;
                }
            }else {
                return Result.failed(2002,"订单支付详情不存在");
            }
            //组团中
        } else if ("TEAMING".equals(order.getStatus())) {
            OrderPay orderPay = this.orderPayRepository.findOneByOrderId(order.getId());
            if (orderPay != null) {
                System.out.println("进来拼团退款了");
                WeixinRefundModel weixinRefundModel = new WeixinRefundModel();
                weixinRefundModel.setFee(orderPay.getPayMoney());
                weixinRefundModel.setDataId(orderPay.getOrderId());
                weixinRefundModel.setParams(new HashMap<>());
                weixinRefundModel.setBody("订单退款");
                weixinRefundModel.setTradeId(orderPay.getTradeId());
                weixinRefundModel.setDataType("订单退款");
                weixinRefundModel.setNotifyUrl("/orderPay/responseWeixinRefundOrderNotify");
                Result result = this.weixinTradeService.requestWeixinRefund(weixinRefundModel);
                //退款成功
                if (0 == result.getCode()){
                    order.setStatus("CANCEL");
                    this.orderRepository.saveAndFlush(order);
                    return Result.ok();
                }else {
                    return result;
                }
            }else {
                return Result.failed(2002,"订单支付详情不存在");
            }
        }
        this.orderRepository.saveAndFlush(order);
        return Result.ok();
    }


    public QueryResults<OrderView> pageOrderBySeller(Long sellerUserId, int pageNum, int pageSize) {
        if (Objects.isNull(sellerUserId)){
            sellerUserId = this.userSessionManager.getUserId();
        }
        QOrder qOrder = QOrder.order;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(sellerUserId)){
            builder.and(qOrder.sellerUserId.eq(sellerUserId));
        }
        QueryResults<OrderView> orderViewQueryResults = queryFactory.select(
                        Projections.bean(
                                OrderView.class,
                                qOrder.shopId,
                                qOrder.status,
                                qOrder.userId,
                                qOrder.sellerUserId,
                                qOrder.code,
                                qOrder.payTime,
                                qOrder.payChannel,
                                qOrder.orderAmount,
                                qOrder.orderFee,
                                qOrder.orderPayFee,
                                qOrder.opexManagerFee,
                                qOrder.goodsFee,
                                qOrder.freightFee,
                                qOrder.preferentialFee,
                                qOrder.type,
                                qOrder.distributionType,
                                qOrder.buyerRemark,
                                qOrder.remindSendTime,
                                qOrder.sendTime,
                                qOrder.remindSendTime,
                                qMember.mobile,
                                qMember.name.as("userName")
                        )
                ).from(qOrder)
                .leftJoin(qMember).on(qOrder.userId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
        //对分页结果进行处理
        List<OrderView> results = orderViewQueryResults.getResults();
        // 创建一个用于存储修改后元组对象的列表
        List<OrderView> modifiedResults = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(results)) {
            Set<Long> orderIds = (Set<Long>)results.stream().map(OrderView::getId).collect(Collectors.toSet());
            List<OrderItem> orderItems = this.orderItemRepository.findListByOrderIds(orderIds);
            for (OrderView view : results) {
                List<OrderItem> orderItemListViews = (List<OrderItem>)orderItems.stream().filter(orderItemListView -> orderItemListView.getOrderId().equals(view.getId())).collect(Collectors.toList());
                view.setOrderItems(orderItemListViews);
                // 将修改后的元组对象添加到列表中
                modifiedResults.add(view);
            }
        }
        // 创建一个新的QueryResults对象，包含修改后的分页记录
        QueryResults<OrderView> modifiedQueryResults = new QueryResults<>(
                modifiedResults,
                orderViewQueryResults.getTotal(),
                orderViewQueryResults.getOffset(),
                orderViewQueryResults.getLimit()
        );
        return modifiedQueryResults;
    }



    public QueryResults<OrderBuyerView> pageOrderByBuyer(Long userId, String status, Set<String> types, int pageNum, int pageSize) {
        if (Objects.isNull(userId)){
            userId = this.userSessionManager.getUserId();
        }
        QOrder qOrder = QOrder.order;
        QSellerShop qSellerShop = QSellerShop.sellerShop;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(userId)){
            builder.and(qOrder.userId.eq(userId));
        }
        if (!Objects.isNull(status)){
            builder.and(qOrder.status.eq(status));
        }
        if (CollectionUtils.isNotEmpty(types)){
            builder.and(qOrder.type.in(types));
        }
        QueryResults<OrderBuyerView> orderBuyerViewQueryResults = queryFactory.select(
                        Projections.bean(
                                OrderBuyerView.class,
                                qOrder.id.as("orderId"),
                                qOrder.status,
                                qOrder.code,
                                qOrder.orderFee,
                                qOrder.type,
                                qSellerShop.iconPath.as("sellerIconPath"),
                                qSellerShop.id.as("sellerUserId"),
                                qSellerShop.name.as("sellerName")
                        )
                ).from(qOrder)
                .leftJoin(qSellerShop).on(qOrder.sellerUserId.eq(qSellerShop.fUserId).and(qSellerShop.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
        //对分页结果进行处理
        List<OrderBuyerView> results = orderBuyerViewQueryResults.getResults();
        // 创建一个用于存储修改后元组对象的列表
        List<OrderBuyerView> modifiedResults = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(results)) {
            Set<Long> orderIds = (Set<Long>)results.stream().map(OrderBuyerView::getOrderId).collect(Collectors.toSet());
            List<OrderItem> orderItems = this.orderItemRepository.findListByOrderIds(orderIds);
            for (OrderBuyerView view : results) {
                List<OrderItem> orderItemListViews = (List<OrderItem>)orderItems.stream().filter(orderItemListView -> orderItemListView.getOrderId().equals(view.getOrderId())).collect(Collectors.toList());
                List<OrderBuyerViewSon> orderBuyerViewSonList = new ArrayList<>();
                for (OrderItem orderItem : orderItemListViews) {
                    OrderBuyerViewSon orderBuyerViewSon = new OrderBuyerViewSon();
                    BeanUtils.copyProperties(orderItem, orderBuyerViewSon);
                    orderBuyerViewSonList.add(orderBuyerViewSon);
                }
                view.setOrderItems(orderBuyerViewSonList);
            }
        }
        // 创建一个新的QueryResults对象，包含修改后的分页记录
        QueryResults<OrderBuyerView> modifiedQueryResults = new QueryResults<>(
                modifiedResults,
                orderBuyerViewQueryResults.getTotal(),
                orderBuyerViewQueryResults.getOffset(),
                orderBuyerViewQueryResults.getLimit()
        );
        return modifiedQueryResults;
    }
    @Transactional
    //@ANoRepeatRequest
    public Result saveRemindSend(Long orderId) {
        Order order = (Order)this.orderRepository.findById(orderId).get();
        if (order != null) {
            if (1 == order.getRemindSend().intValue()) {
                return Result.failed(100,"您已提醒过卖家发货");
            }
            order.setRemindSend(Integer.valueOf(1));
            order.setRemindSendTime(new Date());
            this.orderRepository.saveAndFlush(order);
        }
        return Result.ok();
    }
    @Transactional
    public Result sendOrder(OrderSendModel model) {
        Order order = (Order)this.orderRepository.findById(model.getOrderId()).get();
        if (order == null) {
            return Result.failed(100,"订单不存在");
        }
        OrderLogisticsModel logisticsModel = new OrderLogisticsModel();
        BeanUtils.copyProperties(model, logisticsModel);
        OrderAddress orderAddress = this.orderAddressService.findByOrderIdAndType(order.getId(), "COMMON");
        logisticsModel.setReceivePeople(orderAddress.getName());
        logisticsModel.setReceivePhone(orderAddress.getTelephone());
        logisticsModel.setReceiveAddress(String.format("%s%s%s%s", new Object[] { orderAddress.getProvince(), orderAddress.getCity(), orderAddress
                .getArea(), orderAddress.getDetail() }));
        logisticsModel.setOrderType("GOODS_ORDER");
        this.orderLogisticsService.saveOrderLogistics(logisticsModel);
        order.setStatus("SENDED");
        order.setSendTime(new Date());
        this.orderRepository.saveAndFlush(order);
        this.orderItemRepository.updateStatusByOrderId(model.getOrderId(),"SENDED");
        return Result.ok();
    }

    @Transactional
    public Result seeLogistics(Long orderId) {
        Order order = this.orderRepository.findById(orderId).get();
        if (order != null) {
            OrderLogistics orderLogistics = this.orderLogisticsRepository.findByOrderId(order.getId());
            if (orderLogistics == null) {
                return Result.failed(100,"订单不存在发货信息");
            }
            JSONObject jsonObject = Express100Util.getQuery(orderLogistics.getLogisticsCompanyCode(), orderLogistics.getCourierNumber());
            orderLogistics.setLogisticsInfo(jsonObject.toString());
            this.orderLogisticsRepository.saveAndFlush(orderLogistics);
        }
        return Result.ok();
    }

    @Transactional
    public void orderPayTimeoutInterval() {
        Integer teamTimeoutMinuteStr = 30;
        List<Order> timeoutOrders = this.orderRepository.findByTimeout(teamTimeoutMinuteStr);
        if (CollectionUtils.isNotEmpty(timeoutOrders)) {
            for (Order order : timeoutOrders) {
                order.setStatus("TIMEOUT");
                this.orderRepository.saveAndFlush(order);
            }
        }
    }

    @Transactional
    public void orderAutomaticReceiveInterval() {
        List<Order> orderList = this.orderRepository.findSevenDaySendOrder();
        if (CollectionUtils.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                this.orderService.receiveOrder(order.getId());
            }
        }
    }

    @Transactional
    //@ANoRepeatRequest
    public synchronized Result receiveOrder(Long orderId) {
        Order order = (Order)this.orderRepository.findById(orderId).get();
        if (order == null) {
            return Result.failed(100,"订单不存在");
        }
        order.setStatus("RECEIVED");
        this.orderRepository.saveAndFlush(order);
        this.orderItemRepository.updateStatusByOrderId(orderId,"RECEIVED");
        //TODO 下面这个不知道什么逻辑，问一下懿哥
        //if (order.getSellerUserId().longValue() != 1L);
        return Result.ok();
    }
    public Result<OrderDetailView> detailOrderByShop(Long orderId) {
        Long userId = this.userSessionManager.getUserId();
        Order order = (Order)this.orderRepository.findById(orderId).get();
        if (order == null) {
            return Result.failed(100,"订单信息不存在");
        }
        if (!order.getDistributionType().equals("ONESELF_TAKE")) {
            return Result.failed(100,"该订单未设置自提点");
        }
        Shop shop = (Shop)this.shopRepository.findById(order.getShopId()).get();
        if (shop == null) {
            return Result.failed(100,"订单自提点已被删除，无法操作");
        }
        if (!userId.equals(shop.getUserId())) {
            return Result.failed(100,"您不是该自提点管理员，无法操作");
        }
        OrderDetailView view = new OrderDetailView();
        BeanUtils.copyProperties(order, view);
        view.setType(order.getType());
        view.setDistributionType(order.getDistributionType());
        view.setStatus(order.getStatus());
        SellerShop sellerShop = this.sellerShopRepository.findByUserId(view.getSellerUserId());
        if (sellerShop != null) {
            view.setSellerShopName(sellerShop.getName());
        }
        List<OrderItem> orderItems = this.orderItemRepository.findByOrderId(view.getId());
        view.setOrderItems(orderItems);
        view.setShop(shop);
        return Result.ok(view);
    }


    @Transactional
    public Result saveOrderByShopCart(OrderByShopCartModel model) {
        Long userId = this.userSessionManager.getUserId();
        if (model.getDistributionType().equals("MAIL") && model.getAddressId() == null) {
            return Result.failed(101,"请选择收货地址");
        }
        if (model.getDistributionType().equals("ONESELF_TAKE") && model.getShopId() == null) {
            return Result.failed(102,"请选择自提门店");
        }
        Set<Long> sellerUserIds = model.getSellerOrderList().stream().map(SellerOrderModel::getSellerUserId).collect(Collectors.toSet());
        List<SellerShop> sellerShopList = this.sellerShopRepository.findByUserIds(sellerUserIds);
        if (CollectionUtils.isEmpty(sellerShopList)) {
            return Result.failed(103,"商家店铺不存在或已下架");
        }
        Map<Long, SellerShop> sellerShopMap = (Map<Long, SellerShop>)sellerShopList.stream().collect(Collectors.toMap(SellerShop::getfUserId, sellerShop -> sellerShop));
        MemberCoupon memberCoupon = null;
        if (model.getCouponMemberId() != null) {
            memberCoupon = this.memberCouponRepository.findById(model.getCouponMemberId()).get();
            if (memberCoupon == null) {
                return Result.failed(104,"优惠劵不存在");
            }
            if (memberCoupon.getExpireTime().compareTo(new Date()) >= 0) {
                return Result.failed(105,"优惠劵已过期");
            }
            //NOT_USE("待使用"),USE("已使用"),EXPIRE("已过期");
            if (!memberCoupon.getStatus().equals("NOT_USE")) {
                return Result.failed(106,"优惠劵待使用");
            }
        }
        Set<Long> orderItemIds = new HashSet<>();
        for (SellerOrderModel sellerOrderModel : model.getSellerOrderList()) {
            orderItemIds.addAll(sellerOrderModel.getOrderItemIds());
        }
        List<OrderItem> orderItems = this.orderItemRepository.findAllById(orderItemIds);
        if (CollectionUtils.isEmpty(orderItems) || orderItems.size() != orderItemIds.size()) {
            return Result.failed(107,"订单错误，请重新进入此页面");
        }
        Set<Long> goodsPriceIds = (Set<Long>)orderItems.stream().map(OrderItem::getGoodsPriceId).collect(Collectors.toSet());
        List<GoodsPrice> goodsPriceList = this.goodsPriceRepository.findAllById(goodsPriceIds);
        if (CollectionUtils.isEmpty(goodsPriceList) || goodsPriceList.size() != goodsPriceIds.size()) {
            return Result.failed(107,"您选择的商品包含已下架的规格，请移除后再提交订单");
        }
        Set<Long> goodsIds = (Set<Long>)orderItems.stream().map(OrderItem::getGoodsId).collect(Collectors.toSet());
        List<Goods> goodsList = this.goodsRepository.findAllById(goodsIds);
        if (CollectionUtils.isEmpty(goodsList) || goodsList.size() != goodsIds.size()) {
            return Result.failed(108,"您选择的商品包含下架商品，请移除后再提交订单");
        }
        Map<Long, Goods> goodsMap = (Map<Long, Goods>)goodsList.stream().collect(Collectors.toMap(Goods::getId, goods -> goods));
        Map<Long, GoodsPrice> goodsPriceMap = (Map<Long, GoodsPrice>)goodsPriceList.stream().collect(Collectors.toMap(GoodsPrice::getId, goodsPrice -> goodsPrice));
        if (model.getType().equals("SECKILL")) {
            SeckillTime seckillTime = this.seckillTimeRepository.findCurrentSeckillTime().get(0);
            if (seckillTime == null) {
                return Result.failed(109,"当前商品秒杀活动已结束");
            }
            SeckillGoods seckillGoods = this.seckillGoodsRepository.findByGoodsIdAndSeckillTimeId(((OrderItem)orderItems.get(0)).getGoodsId(), seckillTime.getId());
            if (seckillGoods == null) {
                return Result.failed(109,"当前商品未开启秒杀活动");
            }
        } else if (model.getType().equals("TEAM")) {

            TeamGoods teamGoods = this.teamGoodsRepository.findByGoodsId(((OrderItem)orderItems.get(0)).getGoodsId());
            if (teamGoods == null) {
                return Result.failed(110,"当前商品未开启拼团活动");
            }
        }
        Address address = null;
        //MAIL("快递配送"),ONESELF_TAKE("门店自提")
        if (model.getDistributionType().equals("MAIL")) {
            address = this.addressRepository.findByAddress(model.getAddressId());
        }
        List<Order> orderList = new ArrayList<>();
        for (int i = 0; i < model.getSellerOrderList().size(); i++) {
            SellerOrderModel sellerOrderModel = model.getSellerOrderList().get(i);
            SellerShop sellerShop = sellerShopMap.get(sellerOrderModel.getSellerUserId());
            if (sellerShop == null) {
                return Result.failed(111,"订单中包含不存在的店铺");
            }
            Order order = new Order();
            order.setId(Snowflake.generateId());
            order.setCode(generateGoodsOrderCode());
            order.setCouponMemberId(model.getCouponMemberId());
            order.setType(model.getType());
            order.setDistributionType(model.getDistributionType());
            order.setBuyerRemark(sellerOrderModel.getRemark());
            order.setShopId(model.getShopId());
            order.setStatus("UN_PAY");
            order.setUserId(userId);
            order.setSellerUserId(sellerShop.getfUserId());
            this.orderRepository.save(order);
            List<OrderItem> orderItemList = (List<OrderItem>)orderItems.stream().filter(orderItem -> {
                Goods goods = (Goods)goodsMap.get(orderItem.getGoodsId());
                return (goods != null && goods.getSellerUserId().equals(sellerOrderModel.getSellerUserId()));
            }).collect(Collectors.toList());
            for (OrderItem orderItem : orderItemList) {
                Goods goods = goodsMap.get(orderItem.getGoodsId());
                GoodsPrice goodsPrice = goodsPriceMap.get(orderItem.getGoodsPriceId());
                if (model.getType().equals("COMMON")) {
                    orderItem.setGoodsPrice(goodsPrice.getPrice());
                } else if ("SECKILL".equals(model.getType())) {
                    orderItem.setGoodsPrice(goodsPrice.getSeckillPrice());
                } else {
                    orderItem.setGoodsPrice(goodsPrice.getGroupPurchasePrice());
                }
                orderItem.setItemPrice(orderItem.getGoodsPrice().multiply(new BigDecimal(orderItem.getGoodsAmount().intValue())));
                orderItem.setGoodsName(goods.getName());
                orderItem.setGoodsDes(goods.getDis());
                orderItem.setIconPath(goods.getIconPath());
                orderItem.setStatus("UN_PAY");
                order.setGoodsFee(order.getGoodsFee().add(orderItem.getItemPrice()));
                order.setOrderAmount(Integer.valueOf(order.getOrderAmount().intValue() + orderItem.getGoodsAmount().intValue()));
                orderItem.setOrderId(order.getId());
            }
            if (order.getDistributionType().equals("MAIL")) {
                this.orderAddressService.saveOrderAddress(order.getId(), model.getAddressId(), "COMMON");
            } else if (order.getDistributionType().equals("ONESELF_TAKE")) {
                order.setFreightFee(BigDecimal.ZERO);
            }
            order.setOrderFee(order.getGoodsFee());
            this.orderRepository.saveAndFlush(order);
            orderList.add(order);
        }
        BigDecimal orderFee = orderList.stream().map(Order::getGoodsFee).reduce(BigDecimal.ZERO, BigDecimal::add);
        Set<String> orderIds = (Set<String>)orderList.stream().map(order -> String.valueOf(order.getId())).collect(Collectors.toSet());
        String orderIdsStr = String.join(",", (Iterable)orderIds);
        Map<String,Object> map = new HashMap<>();
        map.put("orderIdsStr",orderIdsStr);
        map.put("orderFee",orderFee.setScale(2, 1));
        return Result.ok(map);
    }

    private String generateGoodsOrderCode() {
        StringBuilder code = new StringBuilder();
        code.append(DateUtil.formatDate(new Date(), "yyyyMMddHHmmss"));
        Double codeRandom = Double.valueOf(Math.random() * 10000.0D);
        code.append(codeRandom.intValue());
        return code.toString();
    }

    public Result saveModel(OrderModel model) {
        Order order = new Order();
        order.setId(Snowflake.generateId());
        BeanUtils.copyProperties(model, order);
        orderRepository.save(order);
        return Result.ok();
    }

    public Result delete(Long orderId) {
        orderRepository.deleteById(orderId);
        return Result.ok();
    }
}
